#!/usr/bin/python

import os
import numpy
from collections import Counter
from pylab import *
import tables,scipy
from scipy import fftpack
from scipy.cluster import vq
from scipy.ndimage import morphology,filters,interpolation
from ocrolib import docproc,improc
import pyflann
import random
import tables
from multiprocessing import Pool
import fcntl
from pdb import pm

def showgrid3(data,nimages=1024):
    """Show a data array as a grid of image."""
    clf()
    r = int(sqrt(nimages))
    w,h,d = data[0].shape
    image = zeros((r*h,r*w,3))
    for i in range(min(len(data),nimages)):
        im = data[i]
        im = im.reshape(w,h,3)
        image[(i/r)*h:(i/r+1)*h,(i%r)*w:(i%r+1)*w,:] = im
    imshow(image.reshape(r*h,r*w,3))

import argparse
parser = argparse.ArgumentParser(
    description = "Show patches in a grid."
    )
parser.add_argument('input',default='patches.h5',help="data file")
parser.add_argument('-t','--table',default="/patches")
parser.add_argument('-n','--nimages',default=1024,type=int,help="number of patches to display")
args = parser.parse_args()

db = tables.openFile(args.input)

nsamples = len(db.root.patches)

for i in range(0,nsamples,args.nimages):
    clf()
    data = db.root.patches[i:i+args.nimages]
    mimgs = db.root.patches[i:i+args.nimages]
    if "sigmas" in dir(db.root):
        msigs = db.root.sigmas[i:i+args.nimages]
    else:
        msigs = mimgs
    imgs = transpose(array([mimgs,msigs,zeros(msigs.shape)]),[1,2,3,0])
    showgrid3(imgs,nimages=args.nimages)
    ginput(1,36000)
